#include "kx/X11Helper.h"
#include "X11Helper.h"

bool Kx::X11Helper::OpenDisplay()
{
    this->m_Display = XOpenDisplay(NULL);

    return m_Display;
}

int Kx::X11Helper::CloseDisplay()
{
    XCloseDisplay(m_Display);
}

std::vector<Kx::X11Window> Kx::X11Helper::GetAllWindows(WindowFilter filter)
{
    std::vector<Kx::X11Window> res;

    Window root = DefaultRootWindow(m_Display);

    CaptureWindows(m_Display, root, res, filter);
    return res;
}

void Kx::X11Helper::CaptureWindows(Display *display, Window window, std::vector<Kx::X11Window> &windows_info,  
WindowFilter filter)
{
    Window root_return;
    Window parent_return;
    Window *children_return;
    unsigned int num_children_return;
    XQueryTree(display, window, &root_return, &parent_return, &children_return, &num_children_return);

    for (unsigned int i = 0; i < num_children_return; ++i)
    {
        Kx::X11Window newInst(m_Display, children_return[i]);
        if(filter(newInst))
        {
            windows_info.emplace_back(newInst);
        }
        CaptureWindows(display, children_return[i], windows_info, filter);
    }

    XFree(children_return);
}

